<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Class-based views &mdash; Django 1.7.8.dev20150401230226 documentation</title>
    
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../../',
        VERSION:     '1.7.8.dev20150401230226',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <link rel="top" title="Django 1.7.8.dev20150401230226 documentation" href="../../index.html" />
    <link rel="up" title="Using Django" href="../index.html" />
    <link rel="next" title="Introduction to Class-based views" href="intro.html" />
    <link rel="prev" title="The Django template language" href="../templates.html" />



 
<script type="text/javascript" src="../../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head>
  <body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 1.7.8.dev20150401230226 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="../templates.html" title="The Django template language">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="intro.html" title="Introduction to Class-based views">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-class-based-views-index">
            
  <div class="section" id="s-class-based-views">
<span id="class-based-views"></span><h1>Class-based views<a class="headerlink" href="#class-based-views" title="Permalink to this headline">¶</a></h1>
<p>A view is a callable which takes a request and returns a
response. This can be more than just a function, and Django provides
an example of some classes which can be used as views. These allow you
to structure your views and reuse code by harnessing inheritance and
mixins. There are also some generic views for simple tasks which we&#8217;ll
get to later, but you may want to design your own structure of
reusable views which suits your use case. For full details, see the
<a class="reference internal" href="../../ref/class-based-views/index.html"><em>class-based views reference documentation</em></a>.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="intro.html">Introduction to Class-based views</a></li>
<li class="toctree-l1"><a class="reference internal" href="generic-display.html">Built-in Class-based generic views</a></li>
<li class="toctree-l1"><a class="reference internal" href="generic-editing.html">Form handling with class-based views</a></li>
<li class="toctree-l1"><a class="reference internal" href="mixins.html">Using mixins with class-based views</a></li>
</ul>
</div>
<div class="section" id="s-basic-examples">
<span id="basic-examples"></span><h2>Basic examples<a class="headerlink" href="#basic-examples" title="Permalink to this headline">¶</a></h2>
<p>Django provides base view classes which will suit a wide range of applications.
All views inherit from the <a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.View" title="django.views.generic.base.View"><tt class="xref py py-class docutils literal"><span class="pre">View</span></tt></a> class, which
handles linking the view in to the URLs, HTTP method dispatching and other
simple features. <a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.RedirectView" title="django.views.generic.base.RedirectView"><tt class="xref py py-class docutils literal"><span class="pre">RedirectView</span></tt></a> is for a
simple HTTP redirect, and <a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.TemplateView" title="django.views.generic.base.TemplateView"><tt class="xref py py-class docutils literal"><span class="pre">TemplateView</span></tt></a>
extends the base class to make it also render a template.</p>
</div>
<div class="section" id="s-simple-usage-in-your-urlconf">
<span id="simple-usage-in-your-urlconf"></span><h2>Simple usage in your URLconf<a class="headerlink" href="#simple-usage-in-your-urlconf" title="Permalink to this headline">¶</a></h2>
<p>The simplest way to use generic views is to create them directly in your
URLconf. If you&#8217;re only changing a few simple attributes on a class-based view,
you can simply pass them into the
<a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.View.as_view" title="django.views.generic.base.View.as_view"><tt class="xref py py-meth docutils literal"><span class="pre">as_view()</span></tt></a> method call itself:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">patterns</span>
<span class="kn">from</span> <span class="nn">django.views.generic</span> <span class="kn">import</span> <span class="n">TemplateView</span>

<span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">&#39;&#39;</span><span class="p">,</span>
    <span class="p">(</span><span class="s">r&#39;^about/&#39;</span><span class="p">,</span> <span class="n">TemplateView</span><span class="o">.</span><span class="n">as_view</span><span class="p">(</span><span class="n">template_name</span><span class="o">=</span><span class="s">&quot;about.html&quot;</span><span class="p">)),</span>
<span class="p">)</span>
</pre></div>
</div>
<p>Any arguments passed to <a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.View.as_view" title="django.views.generic.base.View.as_view"><tt class="xref py py-meth docutils literal"><span class="pre">as_view()</span></tt></a> will
override attributes set on the class. In this example, we set <tt class="docutils literal"><span class="pre">template_name</span></tt>
on the <tt class="docutils literal"><span class="pre">TemplateView</span></tt>. A similar overriding pattern can be used for the
<tt class="docutils literal"><span class="pre">url</span></tt> attribute on <a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.RedirectView" title="django.views.generic.base.RedirectView"><tt class="xref py py-class docutils literal"><span class="pre">RedirectView</span></tt></a>.</p>
</div>
<div class="section" id="s-subclassing-generic-views">
<span id="subclassing-generic-views"></span><h2>Subclassing generic views<a class="headerlink" href="#subclassing-generic-views" title="Permalink to this headline">¶</a></h2>
<p>The second, more powerful way to use generic views is to inherit from an
existing view and override attributes (such as the <tt class="docutils literal"><span class="pre">template_name</span></tt>) or
methods (such as <tt class="docutils literal"><span class="pre">get_context_data</span></tt>) in your subclass to provide new values
or methods. Consider, for example, a view that just displays one template,
<tt class="docutils literal"><span class="pre">about.html</span></tt>. Django has a generic view to do this -
<a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.TemplateView" title="django.views.generic.base.TemplateView"><tt class="xref py py-class docutils literal"><span class="pre">TemplateView</span></tt></a> - so we can just subclass it,
and override the template name:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># some_app/views.py</span>
<span class="kn">from</span> <span class="nn">django.views.generic</span> <span class="kn">import</span> <span class="n">TemplateView</span>

<span class="k">class</span> <span class="nc">AboutView</span><span class="p">(</span><span class="n">TemplateView</span><span class="p">):</span>
    <span class="n">template_name</span> <span class="o">=</span> <span class="s">&quot;about.html&quot;</span>
</pre></div>
</div>
<p>Then we just need to add this new view into our URLconf.
<a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.TemplateView" title="django.views.generic.base.TemplateView"><tt class="xref py py-class docutils literal"><span class="pre">TemplateView</span></tt></a> is a class, not a function,
so we point the URL to the <a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.View.as_view" title="django.views.generic.base.View.as_view"><tt class="xref py py-meth docutils literal"><span class="pre">as_view()</span></tt></a>
class method instead, which provides a function-like entry to class-based
views:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># urls.py</span>
<span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">patterns</span>
<span class="kn">from</span> <span class="nn">some_app.views</span> <span class="kn">import</span> <span class="n">AboutView</span>

<span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">&#39;&#39;</span><span class="p">,</span>
    <span class="p">(</span><span class="s">r&#39;^about/&#39;</span><span class="p">,</span> <span class="n">AboutView</span><span class="o">.</span><span class="n">as_view</span><span class="p">()),</span>
<span class="p">)</span>
</pre></div>
</div>
<p>For more information on how to use the built in generic views, consult the next
topic on <a class="reference internal" href="generic-display.html"><em>generic class based views</em></a>.</p>
<div class="section" id="s-supporting-other-http-methods">
<span id="s-id1"></span><span id="supporting-other-http-methods"></span><span id="id1"></span><h3>Supporting other HTTP methods<a class="headerlink" href="#supporting-other-http-methods" title="Permalink to this headline">¶</a></h3>
<p>Suppose somebody wants to access our book library over HTTP using the views
as an API. The API client would connect every now and then and download book
data for the books published since last visit. But if no new books appeared
since then, it is a waste of CPU time and bandwidth to fetch the books from the
database, render a full response and send it to the client. It might be
preferable to ask the API when the most recent book was published.</p>
<p>We map the URL to book list view in the URLconf:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">patterns</span>
<span class="kn">from</span> <span class="nn">books.views</span> <span class="kn">import</span> <span class="n">BookListView</span>

<span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">&#39;&#39;</span><span class="p">,</span>
    <span class="p">(</span><span class="s">r&#39;^books/$&#39;</span><span class="p">,</span> <span class="n">BookListView</span><span class="o">.</span><span class="n">as_view</span><span class="p">()),</span>
<span class="p">)</span>
</pre></div>
</div>
<p>And the view:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.http</span> <span class="kn">import</span> <span class="n">HttpResponse</span>
<span class="kn">from</span> <span class="nn">django.views.generic</span> <span class="kn">import</span> <span class="n">ListView</span>
<span class="kn">from</span> <span class="nn">books.models</span> <span class="kn">import</span> <span class="n">Book</span>

<span class="k">class</span> <span class="nc">BookListView</span><span class="p">(</span><span class="n">ListView</span><span class="p">):</span>
    <span class="n">model</span> <span class="o">=</span> <span class="n">Book</span>

    <span class="k">def</span> <span class="nf">head</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="n">last_book</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_queryset</span><span class="p">()</span><span class="o">.</span><span class="n">latest</span><span class="p">(</span><span class="s">&#39;publication_date&#39;</span><span class="p">)</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s">&#39;&#39;</span><span class="p">)</span>
        <span class="c"># RFC 1123 date format</span>
        <span class="n">response</span><span class="p">[</span><span class="s">&#39;Last-Modified&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">last_book</span><span class="o">.</span><span class="n">publication_date</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s">&#39;%a, </span><span class="si">%d</span><span class="s"> %b %Y %H:%M:%S GMT&#39;</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">response</span>
</pre></div>
</div>
<p>If the view is accessed from a <tt class="docutils literal"><span class="pre">GET</span></tt> request, a plain-and-simple object
list is returned in the response (using <tt class="docutils literal"><span class="pre">book_list.html</span></tt> template). But if
the client issues a <tt class="docutils literal"><span class="pre">HEAD</span></tt> request, the response has an empty body and
the <tt class="docutils literal"><span class="pre">Last-Modified</span></tt> header indicates when the most recent book was published.
Based on this information, the client may or may not download the full object
list.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Class-based views</a><ul>
<li><a class="reference internal" href="#basic-examples">Basic examples</a></li>
<li><a class="reference internal" href="#simple-usage-in-your-urlconf">Simple usage in your URLconf</a></li>
<li><a class="reference internal" href="#subclassing-generic-views">Subclassing generic views</a><ul>
<li><a class="reference internal" href="#supporting-other-http-methods">Supporting other HTTP methods</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="../templates.html">The Django template language</a></li>
    
    
      <li>Next: <a href="intro.html">Introduction to Class-based views</a></li>
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../../index.html">Django 1.7.8.dev20150401230226 documentation</a>
        
          <ul><li><a href="../index.html">Using Django</a>
        
        <ul><li>Class-based views</li></ul>
        </li></ul>
      </li>
  </ul>

  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="../../_sources/topics/class-based-views/index.txt"
           rel="nofollow">Show Source</a></li>
  </ul>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Apr 02, 2015</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="../templates.html" title="The Django template language">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="intro.html" title="Introduction to Class-based views">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>